using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Web.Security;
using Lab620.WcfRadiusService.Contracts;
using Lab620.WcfRadiusService.Clutch;

namespace Lab620.WcfRadiusService
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    internal class AuthenticationService : IAuthenticationService, IAccountingService
    {
        #region IAccountingService Members

        public void Account(string userName)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IAuthenticationService Members

        public bool Authenticate(string userName, byte[] password, byte[] authenticator)
        {
            var properties = OperationContext.Current.IncomingMessageProperties;
            var sharedSecretBytes = properties["SharedSecret"] as byte[];
            var profileDb = properties["ProfileSource"];

            bool result = false;
            if (profileDb is IClearTextPasswordProvider)
            {
                var dbPassword = ((IClearTextPasswordProvider)profileDb).GetPassword(userName);
                result = PapAuthenticator.Authenticate(sharedSecretBytes, authenticator, password, dbPassword);
            }
            else
            if (profileDb is MembershipProvider)
            {
                var wirePassword = ReversePapAuth.Reverse(sharedSecretBytes, authenticator, password);
                var membershipProvider = ((MembershipProvider) profileDb);
                result = membershipProvider.ValidateUser(userName, wirePassword);
            }

            if (result)
            {
                var outgoingAttributes = new Dictionary<RadiusAttributeType, object>
                                             {{RadiusAttributeType.UserName, userName}};
                OperationContext.Current.OutgoingMessageProperties.Add("PacketAttributes", outgoingAttributes);
            }

            return result;
        }

        #endregion
    }
}